<template>
  <inline-Modal
    :visible="visible"
    :title="menuName"
    :showOk="false"
    @cancel="handelCancel()"
  >
    <a-button
      type="primary"
      class="add-btn"
      :loading="submitLoading"
      @click="handelOk()"
    >
      确定
    </a-button>
    <div class="editorPage-container">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :hideRequiredMark="false"
      >
        <div class="warp-container">
          <a-row>
            <a-col :span="8">
              <a-form-model-item label="工程类型">
                <!-- <a-select
                  allowClear
                  placeholder="请选择"
                  v-model="form.engType"
                  showSearch
                  :filter-option="filterOption"
                  disabled
                >
                  <a-select-option
                    :value="item.dicItemCode"
                    v-for="item in engineerTypeSource"
                    :key="item.dicItemCode" 
                  >
                    {{ item.dicItemName }}
                  </a-select-option>
                </a-select> -->
                <a-input v-model="form.engType" disabled></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="立项类型" prop="type">
                <a-select
                  allowClear
                  placeholder="请选择"
                  v-model="form.type"
                  showSearch
                  :filter-option="filterOption"
                >
                  <a-select-option
                    :value="item.dicItemCode"
                    v-for="item in approvalTypeSource"
                    :key="item.dicItemCode"
                  >
                    {{ item.dicItemName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="省市县">
                <a-cascader
                  disabled
                  :options="provinceSource"
                  :field-names="{
                    label: 'name',
                    value: 'name',
                    children: 'children',
                  }"
                  placeholder="请选择"
                  v-model="form.workArea"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-form-model-item label="文件">
            <div class="base-container">
              <div class="base-left">
                <div class="tree-container">
                  <a-empty v-if="treeData.length == 0" :description="false" />
                  <a-tree
                    v-else
                    show-icon
                    show-line
                    :expanded-keys="expandedKeys"
                    :auto-expand-parent="autoExpandParent"
                    :selected-keys="selectedKeys"
                    :tree-data="treeData"
                    :replaceFields="{
                      children: 'children',
                      title: 'nodeName',
                      key: 'uuid',
                    }"
                    @expand="onExpand"
                    @select="onSelect"
                  >
                    <!-- 自定义图标 -->
                    <template slot="custom" slot-scope="{ expanded }">
                      <a-icon
                        :type="expanded ? 'folder-open' : 'folder'"
                        theme="filled"
                      />
                    </template>
                    <template slot="title" slot-scope="{ nodeName, uuid }">
                      <div class="custom-tree-title-warp">
                        <div class="title" :title="nodeName">
                          {{ nodeName }}
                        </div>
                        <div class="operate">
                          <!-- 新增 -->
                          <icon-font
                            type="icon-xinjianwenjianjia"
                            class="add-file-button"
                            @click.stop="handleAddFolder({ pid: uuid })"
                          ></icon-font>
                          <!-- 编辑 -->
                          <a-icon
                            type="edit"
                            class="edit-btn"
                            @click.stop="handleAddFolder({ uuid }, 2)"
                          />
                          <!-- 删除 -->
                          <a-icon
                            type="delete"
                            class="delete-btn"
                            @click.stop="deleteFolder(uuid)"
                          />
                        </div>
                      </div>
                    </template>
                  </a-tree>
                </div>
              </div>
              <div class="base-right">
                <div class="upload-groups">
                  <a-button
                    class="cu-btn-primary margin-bottom-xs"
                    icon="cloud-upload"
                    @click="uploadFolder()"
                  >
                    上传
                  </a-button>
                  <a-button
                    class="cu-btn-primary margin-bottom-xs"
                    icon="delete"
                    @click="handleBatchDeleteFile()"
                  >
                    批量删除
                  </a-button>
                  <a-button
                    class="cu-btn-primary margin-bottom-xs"
                    @click="handleMoveModal()"
                    icon="drag"
                  >
                    批量移动
                  </a-button>
                </div>
                <div class="table-file-container">
                  <div class="drag-drop-container">
                    <dragDropUpload
                      :treeItem="currentTreeNode"
                      @onRefresh="getTableData()"
                    ></dragDropUpload>
                  </div>
                  <vxe-table
                    ref="xTable"
                    height="99%"
                    align="left"
                    show-overflow
                    show-header-overflow
                    border="inner"
                    :data="tableData"
                    :column-config="{ resizable: true }"
                    size="small"
                    :loading="loading"
                  >
                    <vxe-table-column width="60">
                      <template #header>
                        <a-checkbox
                          v-model="allChecked"
                          :indeterminate="indeterminate"
                          @change="allClick($event)"
                        >
                        </a-checkbox>
                      </template>
                      <template #default="{ row }">
                        <a-checkbox
                          v-model="row.select"
                          @change="changeItem($event, row)"
                        >
                        </a-checkbox>
                      </template>
                    </vxe-table-column>
                    <vxe-column type="seq" width="80" title="序号"></vxe-column>
                    <vxe-column
                      field="name"
                      title="文件名称"
                      align="left"
                      min-width="300"
                    >
                      <template #default="{ row }">
                        <div class="table-file-name">
                          <div
                            class="icon"
                            :class="[getFileIconName(row.name)]"
                          ></div>
                          <div class="name" @click="handelFileModal(row)">
                            {{ row.name }}
                          </div>
                        </div>
                      </template>
                    </vxe-column>
                    <vxe-column field="creator" title="上传人"> </vxe-column>
                    <vxe-column field="createTime" title="上传时间">
                    </vxe-column>
                    <vxe-column title="操作" width="100">
                      <template #default="{ row}">
                        <div class="files-icon">
                          <!-- 预览 -->
                          <a-tooltip placement="top">
                            <template slot="title">
                              预览
                            </template>
                            <a-icon
                              type="eye"
                              class="preview-btn"
                              @click="handelFileModal(row)"
                            />
                          </a-tooltip>
                          <!-- 下载 -->
                          <a-tooltip placement="top" v-action:xmlx_download>
                            <template slot="title">
                              下载
                            </template>
                            <a-icon
                              type="download"
                              class="download-btn"
                              @click="downloadFile(row)"
                            />
                          </a-tooltip>
                        </div>
                      </template>
                    </vxe-column>
                  </vxe-table>
                </div>
              </div>
            </div>
          </a-form-model-item>
          <a-form-model-item label="备注">
            <a-textarea v-model="form.remark" :rows="4"></a-textarea>
          </a-form-model-item>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="提交人">
                <a-input v-model="form.creator" disabled></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="提交时间">
                <a-input v-model="form.createTime" disabled></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
        </div>
      </a-form-model>
    </div>
    <!-- 多文件 -->
    <viewFileModal
      :visible.sync="viewFileModal.visible"
      :fileList="viewFileModal.fileList"
      :subtitle="viewFileModal.name"
      :replaceFields="{
        fileName: 'name',
      }"
    ></viewFileModal>
    <!-- 单文件 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
    <!-- 新建目录 -->
    <addFolderModal
      :visible.sync="addFolderModal.visible"
      :parameter="addFolderModal.soucre"
      :operateType="addFolderModal.operateType"
      @onRefresh="getTreeData()"
    ></addFolderModal>
    <!-- 上传 -->
    <uploadFileModal
      :visible.sync="uploadFileModal.visible"
      :treeItem="currentTreeNode"
      @onRefresh="getTableData()"
    ></uploadFileModal>
    <!-- 批量移动 -->
    <moveModal
      :visible.sync="moveModal.visible"
      :parameter="moveModal.source"
      @moveChange="handleMoveChange()"
    ></moveModal>
  </inline-Modal>
</template>

<script>
import { Icon } from "ant-design-vue";
import iconfrontjs from "@/assets/IconFont/iconfont.js";
const iconFrontUrl = iconfrontjs;
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: iconFrontUrl,
});
import { axios } from "@/utils/request";
import {
  addAttributeByKey,
  flatTreeData,
  getNowDateStr,
  getFileIconName,
} from "@/utils/util.js";
import { mapGetters } from "vuex";
import {
  getToken,
  downloadDfs,
  downLoadBatchFileByArraybuffer,
} from "@/utils/TopVUI";
//多文件预览
import viewFileModal from "@/components/extendCustom/view-file-modal";
//单文件预览
import previewModal from "@/pages/document/minio/previewModal";
//新建目录
import addFolderModal from "./components/addFolderModal.vue";
//上传
import uploadFileModal from "./components/uploadFileModal.vue";
//拖拽上传
import dragDropUpload from "./components/dragDropUpload.vue";
//批量移动
import moveModal from "./components/moveModal.vue";
import areaData from "@/components/_utils/area-json.js";
import { detailCanton, saveCanton } from "@/api/cantonManage";
import { getDicItemByCode } from "@/api/common.js";
export default {
  components: {
    IconFont,
    viewFileModal,
    previewModal,
    addFolderModal,
    uploadFileModal,
    moveModal,
    dragDropUpload,
  },
  props: {
    visible: {
      type: Boolean,
      required: false,
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      form: {
        uuid: "",
        //项目类型
        engType: undefined,
        //区域
        workArea: [],
        //立项类型
        type: undefined,
        //备注
        remark: "",
        //创建人
        creator: "",
        //创建时间
        createTime: "",
      },
      rules: {
        engType: [
          {
            required: true,
            message: "请选择项目类型",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择立项类型",
          },
        ],
        workArea: [
          {
            required: true,
            message: "请选择区域",
          },
        ],
      },
      //左侧树
      expandedKeys: [],
      autoExpandParent: true,
      selectedKeys: [],
      treeData: [],
      currentTreeNode: {},
      //列表
      loading: false,
      tableData: [],
      //多文件预览
      viewFileModal: {
        name: "",
        visible: false,
        fileList: [],
      },
      //单文件预览
      previewModal: {
        visible: false,
        loading: false,
      },
      //新建目录
      addFolderModal: {
        visible: false,
        soucre: {},
        operateType: 1,
      },
      //上传
      uploadFileModal: {
        visible: false,
      },
      //复选框
      allChecked: false,
      indeterminate: false,
      checkRowKeys: [],
      //批量移动弹窗
      moveModal: {
        visible: false,
        source: {},
      },
      //
      submitLoading: false,
      //省市区
      provinceSource: areaData,
      //项目类型
      engineerTypeSource: [],
      //立项类型
      approvalTypeSource: [],
    };
  },
  computed: {
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
    menuName() {
      let { title } = this.$route.meta;
      return title;
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    getFileIconName,
    async getData() {
      //项目类型
      //   this.engineerTypeSource = await this.getDicCodeData("engineeringType");
      //立项类型
      this.approvalTypeSource = await this.getDicCodeData(
        "projectApprovalType"
      );
      await this.getDetail();
      await this.getTreeData();
    },

    //查询字典表
    getDicCodeData(dicCode = "") {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: dicCode })
          .then((res) => {
            let { data } = res;
            resolve(data);
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },

    replaceString(str) {
      return str.replace(/@/g, ">");
    },

    uploadFolder() {
      this.uploadFileModal.visible = true;
    },

    //新建目录
    handleAddFolder(row, type) {
      this.addFolderModal.operateType = type;
      this.addFolderModal.soucre = row;
      this.addFolderModal.visible = true;
    },

    //删除目录
    deleteFolder(uid = "") {
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          return new Promise((resolve, reject) => {
            that
              .$post(
                `/probusiness/projectInitiationTree/deleteBatch?varchar=${uid}`
              )
              .then((res) => {
                let { statusCode, message } = res;
                if (statusCode == 200) {
                  that.$message.success("删除成功！");
                  that.getTreeData();
                } else {
                  that.$message.error(message ?? "删除失败，请稍后重试！");
                }
                resolve();
              })
              .catch((_) => {
                reject();
              })
              .finally((_) => {});
          }).catch(() => console.log("Oops errors!"));
        },
      });
    },

    //表单提交
    handelOk() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let { form } = this;
          let formJson = {
            uuid: form.uuid,
            //项目类型
            engType: form?.engType,
            //区域
            workArea: form?.workArea.join("@"),
            //立项类型
            type: form?.type,
            //备注
            remark: form.remark,
          };
          this.submitLoading = true;
          saveCanton(formJson)
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("处理成功", 1.5);
                this.handelCancel();
              } else {
                this.$message.error(res?.message ?? "处理失败");
              }
            })
            .catch((_) => {})
            .finally((_) => {
              this.submitLoading = false;
            });
        }
      });
    },

    //查询详情
    getDetail() {
      detailCanton({
        code: "XMLX",
      })
        .then((res) => {
          this.form = {
            uuid: res.uuid,
            //项目类型
            engType: res?.engTypeDesc,
            //立项类型
            type: res?.type,
            //备注
            remark: res.remark,
            //创建人
            creator: res.creator,
            //创建时间
            createTime: res.createTime,
            //区域
            workArea: res?.workArea ? res?.workArea.split("@") : [],
          };
        })
        .catch((_) => {});
    },
    //查询树
    getTreeData() {
      axios
        .post(
          `/probusiness/projectInitiationTree/getTree`,
          {},
          {
            headers: {
              "Content-Type": "application/json;charset=UTF-8",
            },
          }
        )
        .then((res) => {
          let source = res?.data ?? [];
          let flatData = flatTreeData(source, "children");
          this.expandedKeys = flatData.map((v) => v.uuid).filter((v) => v);
          let filterData = addAttributeByKey(
            null,
            "scopedSlots",
            { icon: "custom" },
            source,
            "children"
          );
          this.treeData = filterData ?? [];
          if (!this.currentTreeNode.uuid) {
            this.currentTreeNode = filterData?.[0] ?? {};
          }
          this.selectedKeys = [this.currentTreeNode.uuid];
          this.getTableData();
        })
        .catch((_) => {});
    },
    //监听树形选择
    onSelect(selectedKeys, info) {
      let { uuid } = info.node.dataRef;
      this.currentTreeNode = info.node.dataRef;
      this.selectedKeys = [uuid];
      this.getTableData();
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    //查询列表
    getTableData() {
      let { uuid } = this.currentTreeNode;
      this.loading = true;
      axios
        .post(
          `/probusiness/projectInitiationFile/getList`,
          { treeUuid: uuid },
          {
            headers: {
              "Content-Type": "application/json;charset=UTF-8",
            },
          }
        )
        .then((res) => {
          this.tableData = res ?? [];
          this.tableData.forEach((item) => {
            if (this.checkRowKeys.includes(item.uuid)) {
              this.$set(item, "select", true);
            } else {
              this.$set(item, "select", false);
            }
          });
          this.resetBatchCheckBox();
        })
        .catch((_) => {
          this.tableData = [];
        })
        .finally((_) => {
          this.loading = false;
        });
    },

    //重置全选按钮
    resetBatchCheckBox() {
      //   this.showHeader = this.tableData.every((v) => v.versionMain == 1);
      //   let filterArray = this.tableData.filter((v) => v.versionMain != 1);
      let filterArray = this.tableData;
      try {
        filterArray.forEach((v) => {
          if (v.select) {
            throw v;
          }
        });
        this.indeterminate = false;
      } catch (error) {
        this.indeterminate = true;
      }
      const ids = filterArray.filter((item) => item.select).map((v) => v.uuid);
      if (ids.length == filterArray.length) {
        this.indeterminate = false;
      }
      if (filterArray.length > 0) {
        this.allChecked = filterArray.every((v) => v.select);
      } else {
        this.allChecked = false;
      }
    },

    //全选
    allClick() {
      this.indeterminate = false;
      if (this.allChecked) {
        this.tableData.forEach((v) => {
          this.$set(v, "select", true);
        });
        // let filterArray = this.tableData.filter((v) => v.versionMain != 1);
        this.checkRowKeys = this.tableData.map((v) => v.uuid);
      } else {
        this.tableData.forEach((v) => {
          this.$set(v, "select", false);
        });
        this.checkRowKeys = [];
      }
    },

    //单选
    changeItem(event, row) {
      let { checked } = event.target;
      let { uuid } = row;
      if (checked) {
        this.checkRowKeys.push(uuid);
        this.checkRowKeys = Array.from(new Set(this.checkRowKeys));
      } else {
        this.checkRowKeys = this.checkRowKeys.filter((v) => v != uuid);
      }
      //   let filterArray = this.tableData.filter((v) => v.versionMain != 1);
      let filterArray = this.tableData;
      this.allChecked = filterArray.every((v) => v.select);
      this.indeterminate =
        !!this.checkRowKeys.length &&
        this.checkRowKeys.length < filterArray.length;
    },

    //批量删除
    handleBatchDeleteFile() {
      if (this.checkRowKeys.length == 0) {
        this.$message.warning("请选择需要删除的文件！");
        return;
      }
      let uuids = this.checkRowKeys;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          axios
            .post(
              `/probusiness/projectInitiationFile/deleteBatch?varchar=${uuids}`,
              {},
              {
                headers: {
                  "Content-Type": "application/json",
                },
              }
            )
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                that.checkRowKeys = [];
                that.getTableData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },

    //批量移动
    handleMoveModal() {
      if (this.checkRowKeys.length == 0) {
        this.$message.warning("请选择需要移动的文件！");
        return;
      }
      let { checkRowKeys } = this;
      this.moveModal.source = {
        fileUuids: checkRowKeys,
      };
      this.moveModal.visible = true;
    },

    handleMoveChange() {
      this.allChecked = false;
      this.indeterminate = false;
      this.checkRowKeys = [];
      this.getTableData();
    },
    //预览
    handelFileModal(row) {
      const fileList = JSON.parse(row?.fileAddress ?? "[]");
      if (fileList.length == 0) {
        return;
      } else if (fileList.length == 1) {
        let { url } = fileList?.[0] ?? {};
        this.previewModal.loading = true;
        this.$refs.previewModal.type = "file";
        this.$refs.previewModal.fileUrl =
          this.kkFileView +
          "/onlinePreview?url=" +
          encodeURIComponent(Base64.encode(url)) +
          "&watermarkTxt=" +
          //水印内容
          encodeURIComponent("") +
          "&token=" +
          getToken();
        this.previewModal.visible = true;
        this.previewModal.loading = false;
      } else {
        this.viewFileModal.name = row.name;
        this.viewFileModal.fileList = fileList ?? [];
        this.viewFileModal.visible = true;
      }
    },

    //下载
    downloadFile(row) {
      const fileList = JSON.parse(row?.fileAddress ?? "[]");
      if (fileList.length == 0) {
        return;
      } else if (fileList.length == 1) {
        let { url } = fileList?.[0] ?? {};
        downloadDfs(url);
      } else {
        this.viewFileModal.name = row.name;
        this.viewFileModal.fileList = fileList ?? [];
        this.viewFileModal.visible = true;
      }
    },
    handelCancel() {
      this.$emit("update:visible", false);
      this.$parent.getData();
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
.modal-full-layout {
  /deep/.ant-form-item {
    display: flex;
    .ant-form-item-label {
      flex-shrink: 0;
      width: 120px;
    }
    .ant-form-item-control-wrapper {
      flex: 1;
      overflow: hidden;
    }
  }
  .add-btn {
    position: absolute;
    top: 10px;
    right: 90px;
  }
  .editorPage-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;

    .warp-container {
      padding-right: 110px;
      box-sizing: border-box;
    }
    .base-container {
      height: 562px;
      overflow: hidden;
      display: flex;
      .base-left {
        width: 300px;
        flex-shrink: 0;
        border-radius: 4px 4px 4px 4px;
        border: 1px solid #d4d7d8;
        margin-right: 10px;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        /deep/.ant-form-item {
          .ant-form-item-label {
            width: 56px;
          }
        }
        .tree-container {
          flex: 1;
          overflow: auto;
          overflow-x: hidden;
          position: relative;
          padding: 0 10px 0 10px;
          /deep/.ant-tree {
            .ant-tree-node-content-wrapper {
              &:hover {
                .operate {
                  .anticon {
                    display: inline-block !important;
                  }
                }
              }
            }
            li {
              width: 100%;
              .ant-tree-node-content-wrapper {
                position: relative;
                width: calc(100% - 25px);
                padding: 0;
                .ant-tree-iconEle {
                  color: #ffca28;
                  font-size: 16px;
                }
                .ant-tree-title {
                  overflow: hidden;
                  display: inline-block;
                  width: calc(100% - 26px);
                  .custom-tree-title-warp {
                    display: flex;
                    width: 100%;
                    .title {
                      flex: 1;
                      overflow: hidden;
                      overflow: hidden;
                      white-space: nowrap;
                      text-overflow: ellipsis;
                    }
                    .operate {
                      flex-shrink: 0;
                      color: #8c8c8c;
                      .anticon {
                        display: none;
                        margin-right: 8px;
                        &:last-of-type {
                          margin-right: 0;
                        }
                      }
                      .add-file-button {
                        font-size: 15px;
                      }
                    }
                  }
                }
              }
            }
          }
          .ant-empty {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
          }
        }
      }
      .base-right {
        width: calc(100% - 310px);
        flex-shrink: 0;
        display: flex;
        flex-direction: column;
        .upload-groups {
          height: 48px;
        }
        .table-file-container {
          flex: 1;
          position: relative;
          .files-icon {
            .anticon {
              cursor: pointer;
              font-size: 18px;
              color: #1677ff;
              margin-right: 16px;
              &:last-of-type {
                margin-right: 0;
              }
            }
            .anticon-download {
              color: #239b53;
            }
            .anticon-delete {
              color: #e43d3d;
            }
          }
          .drag-drop-container {
            z-index: 22;
            position: absolute;
            left: 60px;
            height: 100%;
            width: 80%;
          }
        }
        .table-file-pager {
          flex-shrink: 0;
        }
      }
    }
  }
}
</style>
